from fastapi import UploadFile
from models.ai.config.settings import logger
import os
import uuid

class R:
    def __init__(self, code=200, data=None, msg="操作成功"):
        self.code = code
        self.data = data
        self.msg = msg
        # import sys
        # print(f"R = {sys.path}")

    def to_dict(self):
        return {
            "code": self.code,
            "msg": self.msg,
            "data": self.data,
        }

    @staticmethod
    def data(data):
        return R(data=data).to_dict()

    @staticmethod
    def success():
        return R().to_dict()

    @staticmethod
    def error(msg):
        return R(code=500, msg=msg).to_dict()

"""
    保存文件到某个目录
    @author Charles
"""
async def saveRequestFile(audio: UploadFile,
                    distPath="upload",
                    bufferSize=1024 * 1024):
    file_ext = os.path.splitext(audio.filename)[1]
    new_file_name = str(uuid.uuid4()) + file_ext

    if not os.path.exists(distPath):
        os.makedirs(distPath)
    # # 保存文件
    save_path = os.path.join(distPath, new_file_name)
    logger.info(f"save_path = {save_path}")
    # 保存文件到磁盘
    with open(save_path, "wb") as buffer:
        while True:
            # 分块读取文件内容（避免内存溢出）
            chunk = await audio.read(bufferSize)  # 每次读取1MB
            if not chunk:
                break
            buffer.write(chunk)
    return save_path

async def saveRequestFileByByte(audioBytes,
                          distPath="upload",
                          bufferSize=1024 * 1024):
    new_file_name = str(uuid.uuid4())

    if not os.path.exists(distPath):
        os.makedirs(distPath)
    # # 保存文件
    save_path = os.path.join(distPath, new_file_name)
    logger.info(f"save_path = {save_path}")
    # 保存文件到磁盘
    with open(save_path, "wb") as buffer:
        buffer.write(audioBytes)
    return save_path